import java.util.Arrays;

/**
 * @ClassName Code06_BSNearRight
 * @Description: TODO
 * @Author: JCC
 * @CreateTime: 2023/12/1 20:17
 */
public class Code06_BSNearRight {

    // 在array上，找满足 <= value的最右位置
    /*public static int nearestIndex(int[] array, int value) {
        int len = array.length;
        int L = 0;
        int R = array.length - 1;
        int index = -1;
        while (L <= R) {
            int mid = L + ((R - L) >> 1);
            if (array[mid] < value) {
                L = mid + 1;
            } else if (array[mid] > value) {
                R = mid - 1;
            } else {
                index = mid;
                L = mid + 1;
            }
        }
        return index;
    }*/

    public static int nearestIndex(int[] array, int value) {
        int L = 0;
        int R = array.length - 1;
        int index = -1;
        while (L <= R) {
            int mid = L + ((R - L) >> 1);
            if (array[mid] <= value) {
                index = mid;
                L = mid + 1;
            } else {
                R = mid - 1;
            }
        }
        return index;
    }

    // 测试
    /*public static int test(int[] array, int value) {
        int len = array.length;
        for (int i = 0; i < len; i++) {
            if (array[i] == value) {
                return i;
            }
        }
        return -1;
    }*/
    public static int test(int[] array, int value) {
        /*int len = array.length;
        int index = -1;
        for (int i = 0; i < len; i++) {
            if (array[i] <= value) {
                index = i;
            }
        }
        return index;*/

        int len = array.length;
        for (int i = len - 1; i >= 0; i--) {
            if (array[i] <= value) {
                return i;
            }
        }
        return -1;
    }

    public static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] randArray = new int[(int) (Math.random() * (maxSize + 1))];
        for (int i = 0; i < randArray.length; i++) {
            randArray[i] = (int) (Math.random() * (maxValue + 1) - (int) (Math.random() * maxValue));
        }
        return randArray;
    }

    public static void main(String[] args) {
        int testTimes = 1000;
        int maxSize = 10;
        int maxValue = 1000;
        for (int i = 0; i < testTimes; i++) {
            int[] randArray = generateRandomArray(maxSize, maxValue);
            Arrays.sort(randArray);
            int value = (int) (Math.random() * (maxValue + 1));
            if (nearestIndex(randArray, value) != test(randArray, value)) {
                System.out.println("fucking fucked！！！");
                System.out.println(Arrays.toString(randArray));
                System.out.println(value);
                System.out.println(nearestIndex(randArray, value));
                System.out.println(test(randArray, value));
                return;
            }
        }
        System.out.println("nice！！！");
    }
}
